package com.cjk.foundation.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

public class PropertyUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);

	public static Integer parseIntProperty(ResourceBundle bundle, String propertyName) {
		if (null == bundle || StringUtils.isBlank(propertyName) || !bundle.containsKey(propertyName)) {
			return null;
		}
		String stringVal = bundle.getString(propertyName);
		if (StringUtils.isBlank(stringVal)) {
			return 0;
		}

		Integer retVal;
		try {
			retVal = Integer.valueOf(stringVal);
		} catch (Exception e) {
			retVal = 0;
			logger.error(e.getMessage());
		}

		return retVal;
	}

	public static String parseStringProperty(ResourceBundle bundle, String propertyName) {
		if (null == bundle || StringUtils.isBlank(propertyName) || !bundle.containsKey(propertyName)) {
			return null;
		}

		String stringVal = bundle.getString(propertyName);

		return StringUtils.isBlank(stringVal) ? null : stringVal;
	}

	public static Boolean parseBooleanProperty(ResourceBundle bundle, String propertyName) {
		if (null == bundle || StringUtils.isBlank(propertyName) || !bundle.containsKey(propertyName)) {
			return false;
		}

		String stringVal = bundle.getString(propertyName);
		if(StringUtils.isEmpty(stringVal)){
			return false;
		}
		return Boolean.valueOf(stringVal);

	}

	// property file 必须以..properties结尾
	public static void writeProperties(String propertyFile, String parameterName, String parameterValue) {
		if (parameterValue == null || parameterName == null || propertyFile == null) {
			return;
		}

		ClassPathResource resource = new ClassPathResource(propertyFile);
		String filePath;
		try {
			filePath = resource.getURL().getPath().replace("20%", "");
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		Properties props = new Properties();

		InputStream fis = null;
		OutputStream fos = null;
		try {

			// 如果文件不存在，创建一个新的
			File file = new File(filePath);
			if (!file.exists()) {
				return;
			}

			fis = new FileInputStream(filePath);
			props.load(fis);
			fis.close();

			fos = new FileOutputStream(filePath);
			props.setProperty(parameterName, parameterValue);
			props.store(fos, parameterName);
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (Exception e2) {
			}
		}
	}
}
